﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WSIMServices.model;
using System.IO;
using WSIMCommons;
using System.Data;
using System.Threading;

namespace WSIMServices
{
    // NOTE: If you change the class name "WSIMMessagingOperations" here, you must also update the reference to "WSIMMessagingOperations" in Web.config.
    public class WSIMMessagingOperations : IWSIMMessagingOperations
    {

        #region IWSIMMessagingOperations Members

        public List<Message> GetNewMessages()
        {
            long id = (long)ObjectFactory.GetUserTable().GetID(OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name);
            WSIMMessaging.wsim_message_modelDataTable table;
            table = ObjectFactory.GetMessageTable().GetNewMessages(id);
            
            List<Message> lst = new List<Message>();

            foreach (DataRow row in table.Rows) {
                Message m = new Message();
                m.Sender = (long)row["USER_SENDER"];
                m.Receiver = id;
                m.Text = row["TEXT"].ToString();
                m.MsgDate = (DateTime)row["MSG_DATETIME"];
                m.IsText = ((bool)row["IS_TEXT_MESSAGE"]);


                
                //logica per attachment
                if (!m.IsText)
                {
                    long idMsg = (long)row["ID"];
                    DataRow rowAt = ObjectFactory.GetMessageAttachmentTable().GetDataByMsgID(idMsg).Rows[0];
                    Attachment at = new Attachment();
                    at.Filename = rowAt["FILENAME"].ToString();
                    at.Lenght = (int)rowAt["AT_SIZE"];

                    FileStream inp = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "files\\"+
                        rowAt["ID"].ToString(), FileMode.Open);
                    byte[] bytes = new byte[inp.Length];
                    inp.Read(bytes, 0, (int)inp.Length);
                    //files.UpdateOldFiles(Int32.Parse(tmp.Rows[0][0].ToString()));
                    inp.Close();
                    at.Content = bytes;
                    m.Attachment = at;
                }
                lst.Add(m);
            }

            ObjectFactory.GetMessageTable().UpdateReadMessage(id);

            return lst;

        }

        public List<Message> GetMessagesWithOptions(Options opt)
        {
            throw new NotImplementedException();
        }

        public void SendMessage(Message msg)
        {
            WSIMMessagingTableAdapters.wsim_message_modelTableAdapter mTable = ObjectFactory.GetMessageTable();
            WSIMMessagingTableAdapters.wsim_message_attachmentTableAdapter mAtt = ObjectFactory.GetMessageAttachmentTable();

            long id = WSIMUtilities.GetValidID();
            
            if (!msg.IsText)
            {
                try
                {
                    long attID = WSIMUtilities.GetValidID();
                    string s = AppDomain.CurrentDomain.BaseDirectory +"files\\"+ attID.ToString();
                    if (File.Exists(s)) File.Delete(s);
                    FileStream outf = new FileStream(s, FileMode.CreateNew);
                    outf.Write(msg.Attachment.Content, 0, msg.Attachment.Lenght);
                    outf.Close();

                    mTable.Insert(id, msg.Sender, msg.Receiver, (byte)(msg.IsText ? 1 : 0), msg.Text, msg.MsgDate, 1, null);
                    mAtt.Insert(attID, id, 1, msg.Attachment.Filename, msg.Attachment.Lenght);
                    return;
                }
                catch(Exception ex)
                {
                    throw new Exception(ErrorCodesEnum.W1003_ERROR_IN_FILE_UPLOAD.ToString());
                }
                
            }

            mTable.Insert(id, msg.Sender, msg.Receiver, (byte)(msg.IsText ? 1 : 0), msg.Text, msg.MsgDate, 1, null);
            

        }

        #endregion
    }
}
